//
//  AdaptivePresentationSecondViewController.swift
//  CustomTransitions
//
//  Created by fuyoufang on 2021/10/13.
//

import Foundation
import UIKit

class AdaptivePresentationSecondViewController: BaseSecondViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Adaptive Presentation"
        nextStepButton.isHidden = true
        
        // In the regular environment, AAPLAdaptivePresentationController displays
        // a close button for the presented view controller.  For the compact
        // environment, a 'dismiss' button is added to this view controller's
        // navigationItem.  This button will be picked up and displayed in the
        // navigation bar of the navigation controller returned by
        // -presentationController:viewControllerForAdaptivePresentationStyle:
        let dismissButton = UIBarButtonItem(title: "Dismiss",
                                            style: .plain,
                                            target: self,
                                            action: #selector(dismissButtonAction(sender:)))
        navigationItem.leftBarButtonItem = dismissButton
    }
    
    override var transitioningDelegate: UIViewControllerTransitioningDelegate? {
        didSet {
#warning(
"""
注意设置 presentationController?.delegate 的位置
这里 transitioningDelegate 和 presentationController 为统一个对象，
对 presentation view controller 来说，只有在转场过程中，presentationController 才有值，
设置 presentationController 的 delegate 又要在开始转场之前进行设置，
所以，如果 transitioningDelegate 和 presentationController 不是同一个对象的话，会很难设置。
""")
            // For an adaptive presentation, the presentation controller's delegate
            // must be configured prior to invoking
            // -presentViewController:animated:completion:.  This ensures the
            // presentation is able to properly adapt if the initial presentation
            // environment is compact.
            self.presentationController?.delegate = self
        }
    }
    
    @objc func dismissButtonAction(sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

extension AdaptivePresentationSecondViewController: UIAdaptivePresentationControllerDelegate {
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        // An adaptive presentation may only fallback to
        // UIModalPresentationFullScreen or UIModalPresentationOverFullScreen
        // in the horizontally compact environment.  Other presentation styles
        // are interpreted as UIModalPresentationNone - no adaptation occurs.
        return .fullScreen
    }
    
    func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
        return UINavigationController(rootViewController: self)
    }

}
